package com.itheima.controller;

import com.itheima.domain.Announcement;
import com.itheima.domain.Question;
import com.itheima.domain.User;
import com.itheima.service.AnnouncementService;
import com.itheima.service.AnswerService;
import com.itheima.service.QuestionService;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class  IndexController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private UserService userService;
    @Autowired
    private AnswerService answerService;
    @Autowired
    private AnnouncementService announcementService;

    @RequestMapping("/index")
    public String index(String title, String page, Model model){
        //当前页
        int currentPage = 1;
        int pageCount = 10;
        //获取前端提交数据
        if (title == null){
            title = "";
        }
        if (page != null){
            currentPage = Integer.parseInt(page);
        }
        List<Question> list = questionService.getAllByPage(currentPage, pageCount, title);
        for (Question question: list) {
            Integer uid = question.getUid();
            User user = userService.getById(uid);
            question.setUser(user);

            Integer qid = question.getQid();
            int answeredCount = answerService.answerCount(qid);
            question.setAnswerCount(answeredCount);

        }
        Announcement announcement = announcementService.getAnnouncement();

        List<Question> listUp = questionService.getAllUp();
        Integer totalPage = questionService.getTotalPage(pageCount, title);
        model.addAttribute("totalPage",totalPage);
        model.addAttribute("questionList",list);
        model.addAttribute("questionUpList",listUp);
        model.addAttribute("currentPage",currentPage);
        model.addAttribute("title",title);
        model.addAttribute("announcement",announcement);

        return "index";
    }
}
